package com.example.servicetest.util

import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Color
import java.util.*

object ColorUtil {

    /**
     * 根据RGB色值获取整型颜色
     * @param rgb rgb色值,空代表获取随机颜色
     * @return int型色值
     */
    fun getColorByRgb(rgb: String?): Int {
        var color = Color.WHITE
        try {
            color = if (rgb != null) {
                Color.parseColor(rgb)
            } else {
                Color.parseColor(ranDomColor)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return color
    }

    /**
     * 获取随机颜色
     * @return 随机六位色值
     */
    val ranDomColor: String
        get() {
            val stringBuffer = StringBuffer()
            stringBuffer.append("#")
            for (i in 0..5) {
                stringBuffer.append(randomBeen)
            }
            return stringBuffer.toString()
        }

    /**
     * 获取色值单元
     * @return 单个色值单元值
     */
    val randomBeen: String
        get() {
            var been = ""
            val random = getRandom(16)
            if (random > 9) {
                when (random) {
                    10 -> been = "a"
                    11 -> been = "b"
                    12 -> been = "c"
                    13 -> been = "d"
                    14 -> been = "e"
                    15 -> been = "f"
                }
            } else {
                been = random.toString()
            }
            return been
        }

    /**
     * 获取随机整形数字
     * @return 随机数
     */
    fun getRandom(range: Int): Int {
        val random = Random()
        return random.nextInt(range)
    }


    fun getColorFormResources(context: Context, resId: Int): Array<IntArray> {
        val bitmapNew = BitmapFactory.decodeResource(context.resources, resId)
        // Bitmap bitmapNew1 = bit.copy(Bitmap.Config.RGB_565, true);
        val graylist = Array(bitmapNew.width) {
            IntArray(bitmapNew.height)
        }
        for (i in 0 until bitmapNew.height) {
            for (j in 0 until bitmapNew.width) {
                val col = bitmapNew.getPixel(j, i)
                graylist[j][i] = col
            }
        }
        return graylist
    }

}